﻿#include "ship.h"
#include "dispatcher.h"
#include <mutex>
#include <QDebug>
#include <thread>
#include <chrono>

Ship::Ship(const QString id): m_id(id), m_is_pass(false)
{

}

void Ship::run()
{
    while(true){
        std::unique_lock<std::mutex> lock(Dispatcher::getInstance()->getQueMutex());
        Dispatcher::getInstance()->getCond().wait(lock, [&] {
            return Dispatcher::getInstance()->getIsOnDuty(); });
        applyForLoading();
        break;
    }
    while(!m_is_pass) std::this_thread::sleep_for(std::chrono::milliseconds(20));
    berth();
    loadCargo();
    transportAway();
}

void Ship::berth()
{
    qInfo() << "ship: " << m_id << " berthing...";
    std::this_thread::sleep_for(std::chrono::seconds(1));
}

void Ship::loadCargo()
{
    m_cargo = Dispatcher::getInstance()->distributeCargo();
    qInfo() << "ship id: " << m_id << " loading cargo from dispather, cargo id: " << m_cargo->getId();
    std::this_thread::sleep_for(std::chrono::seconds(1));
}

void Ship::transportAway()
{
    qInfo() << "ship: " << m_id << " transport away the Cargo: " << m_cargo->getId();
    std::this_thread::sleep_for(std::chrono::seconds(1));
    emit loadReady(this);
}

void Ship::applyForLoading()
{
    Dispatcher::getInstance()->inputApplyShipMessage(this->m_id);
}

const QString Ship::getId() const
{
    return m_id;
}

const QString Ship::getCargoId() const
{
    return m_cargo ? m_cargo->getId(): QString();
}

void Ship::setIsPass(const bool is_pass)
{
    m_is_pass = is_pass;
}

